package com.thinkit.bigdata.web.service.impl.bus;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.feature.orm.mybatis.Page;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.PropertiesUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.httpUtil.HttpUtil;
import com.thinkit.bigdata.core.util.thread.ThreadExecutorUtil;
import com.thinkit.bigdata.web.controller.pubmet.PubMethod;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.dao.bus.*;
import com.thinkit.bigdata.web.dao.sec.SysUserMapper;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.*;
import com.thinkit.bigdata.web.model.es.audioEs.Source;
import com.thinkit.bigdata.web.model.es.audioEs.TestInfos;
import com.thinkit.bigdata.web.model.es.audioEs.TestModelRules;
import com.thinkit.bigdata.web.model.es.audioEs.VoiceInfoDto;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.bus.BusModelService;
import com.thinkit.bigdata.web.service.bus.BusWorkTestService;
import com.thinkit.bigdata.web.thread.WorkTestThread;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 *
 * Created by hccl on 2018/10/12.
 */
@Service
public class BusWorkTestServiceImpl implements BusWorkTestService {

    private static Logger logger = Logger.getLogger(BusWorkTestServiceImpl.class);

    @Resource
    private BusWorkTestMapper busWorkTestMapper;

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private BusWktModelMapper busWktModelMapper;

    @Resource
    private BusWktVoiceMapper busWktVoiceMapper;

    @Resource
    private BusModelRuleMapper busModelRuleMapper;

    @Resource
    private BusModelMapper busModelMapper;

    @Resource
    private BusModelService busModelService;

    @Resource
    private ESUtil esUtil;

    @Override
    public HtmlResult getAddTestTaskMeg(HttpServletRequest request) {
        Integer pageNum = Integer.parseInt(request.getParameter("pageNum"));//起始页
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));//每页条数
        BoolQueryBuilder boolQuery = formatQuery(request, "【模型测检添加-获取音频列表-分页】");
        String[] includes = new String[]
                {
                        "serialNumber",
                        "voiceInfo"
                };
        List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                pageNum,
                pageSize,
                boolQuery,
                SystemStatic.crud.formatCloumn("inputTime", SystemStatic.AUDIO_ES_INDEX),
                "desc",
                includes
        );
        return HtmlResult.success(esUtil.strs2Entitys(docList));
    }

    private BoolQueryBuilder formatQuery(HttpServletRequest request, String logTxt) {
        String provinceCodes = request.getParameter("provinceCode");//省份标识
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String seatGroups = request.getParameter("seatGroup");//被质检班组
        String seatIds = request.getParameter("seatIds");//被质检座席工号
        String customerNums = request.getParameter("customerNum");//客户号码
        String customerLevels = request.getParameter("customerLevels");//客户星级
        String customerlocs = request.getParameter("customerloc");//客户归属地
        String serialNumbers = request.getParameter("serialNumber");//录音流水
        String onHooks = request.getParameter("onHook");//挂机方
        String satisfactions = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//重复来电
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        logger.info(logTxt + "minDuration = " + minDuration);
        logger.info(logTxt + "maxDuration = " + maxDuration);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "provinceCode = " + provinceCodes);
        logger.info(logTxt + "seatGroup = " + seatGroups);
        logger.info(logTxt + "seatIds = " + seatIds);
        logger.info(logTxt + "customerNum = " + customerNums);
        logger.info(logTxt + "customerLevels = " + customerLevels);
        logger.info(logTxt + "customerloc = " + customerlocs);
        logger.info(logTxt + "serialNumber = " + serialNumbers);
        logger.info(logTxt + "onHook = " + onHooks);
        logger.info(logTxt + "satisfaction = " + satisfactions);
        logger.info(logTxt + "reCallFlag = " + reCallFlag);
        logger.info(logTxt + "customerSign = " + customerSign);
        logger.info(logTxt + "callDirection = " + callDirection);
        logger.info(logTxt + "callTags = " + callTags);
        logger.info(logTxt + "sysTags = " + sysTags);
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        //callTags
        if (!Strings.isNullOrEmpty(callTags)) {
            BoolQueryBuilder builder = new BoolQueryBuilder();
            for (String callTag : callTags.split(",")) {
                builder.should(
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.wildcardQuery("callTags.tagName", callTag + "*"))
                                .must(QueryBuilders.matchQuery("callTags.proType", BaseEntity.PROTYPE_ZX))
                );
            }
            boolQuery.must(QueryBuilders.nestedQuery(
                    "callTags",
                    builder,
                    ScoreMode.None
            ));
        }
        //sysTags
        if (!Strings.isNullOrEmpty(sysTags)) {
            BoolQueryBuilder builder = new BoolQueryBuilder();
            for (String sysTag : sysTags.split(",")) {
                builder.should(
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.wildcardQuery("callTags.tagName", sysTag + "*"))
                                .mustNot(QueryBuilders.matchQuery("callTags.proType", BaseEntity.PROTYPE_ZX))
                                .must(QueryBuilders.matchQuery("callTags.proValue", BaseEntity.PROVALUE_YES))
                );
            }
            boolQuery.must(QueryBuilders.nestedQuery(
                    "callTags",
                    builder,
                    ScoreMode.None
            ));
        }
        //数据权限
        esUtil.formatQ(boolQuery, null);
        //voiceInfos mes
        if (!Strings.isNullOrEmpty(callDirection)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.callDirection", callDirection));
        }
        if (!Strings.isNullOrEmpty(customerSign)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.customerSign", customerSign));
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.reCallFlag", reCallFlag));
        }
        if (!Strings.isNullOrEmpty(satisfactions)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String satisfaction : satisfactions.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.satisfaction", satisfaction));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(onHooks)) {
            PubMethod.formatOnHook(boolQuery, Arrays.asList(onHooks.split(",")));
        }
        if (!Strings.isNullOrEmpty(seatIds)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String userId : seatIds.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.seatId", userId));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(provinceCodes)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String provinceCode : provinceCodes.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.provinceCode", provinceCode));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(serialNumbers)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String serialNumber : serialNumbers.split(",")) {
                shuldQ.should(QueryBuilders.wildcardQuery("serialNumber", "*" + serialNumber + "*"));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(customerNums)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String customerNum : customerNums.split(",")) {
                shuldQ.should(QueryBuilders.wildcardQuery("voiceInfo.customerNum", "*" + customerNum + "*"));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(customerLevels)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String customerLevel : customerLevels.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.customerLevel", customerLevel));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(customerlocs)) {
            PubMethod.formatPC(boolQuery, Arrays.asList(customerlocs.split(",")));
        }
        if (!Strings.isNullOrEmpty(seatGroups)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String seatGroup : seatGroups.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.groupId", seatGroup));
            }
            boolQuery.must(shuldQ);
        } else {
            //todo坐席组别为空时默认添加该登录角色下可操作的班组
            List<Long> seatGroupIdList = (List<Long>) SecurityUtils.getSubject().getSession().getAttribute("groupIds");
            if (seatGroupIdList != null) {
                BoolQueryBuilder shuldQ = new BoolQueryBuilder();
                for (Long seatGroup : seatGroupIdList) {
                    shuldQ.should(QueryBuilders.matchQuery("voiceInfo.groupId", seatGroup));
                }
                boolQuery.must(shuldQ);
            }
        }
        if (!Strings.isNullOrEmpty(minDuration)) {
            boolQuery.must(QueryBuilders.rangeQuery("voiceInfo.holdDuration").gte(minDuration));
        }
        if (!Strings.isNullOrEmpty(maxDuration)) {
            boolQuery.must(QueryBuilders.rangeQuery("voiceInfo.holdDuration").lte(maxDuration));
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            PubMethod.formatTime(boolQuery, callStartTime, callEndTime);
        }
        return boolQuery;
    }

    @Override
    public List<BusWorkTestWithBLOBs> selectByExample(BusWorkTestExample example) {
        return busWorkTestMapper.selectByExampleWithBLOBs(example);
    }

    @Override
    public HtmlResult selectByExample(Page<BusWorkTestWithBLOBs> page, BusWorkTestExample example) throws Exception {
        List<BusWorkTestWithBLOBs> workTests = busWorkTestMapper.selectByExampleWithBLOBs(page, example);
        List<BusWorkTestCopy> workTestCopies = new ArrayList<>();
        for (BusWorkTest workTest : workTests) {
            BusWorkTestCopy copy = new BusWorkTestCopy();
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            BeanUtils.copyProperties(copy, workTest);
            copy.setCreateuserName(userMapper.selectByPrimaryKey(workTest.getCreateuserid()).getUsername());
            workTestCopies.add(copy);
        }
        return HtmlResult.success(workTestCopies, page.getTotalCount());
    }

    @Override
    public List<BusWorkTestCopy> selectWorkInfos(Map<String, Object> map) {
        return busWorkTestMapper.selectWorkInfos(map);
    }

    @Override
    public List<BusWorkTestCopy> selectWorkInfos(Page page, Map<String, Object> map) {
        List<Map<String, Object>> testWorks = busWorkTestMapper.selectWorkInfos(page, map);
        List<BusWorkTestCopy> dtos = new ArrayList<>();
        for (Map<String, Object> testWork : testWorks) {
            BusWorkTestCopy dto = (BusWorkTestCopy) com.thinkit.bigdata.core.util.bean.BeanUtils.map2Object(testWork, BusWorkTestCopy.class);
            dtos.add(dto);
        }
        return dtos;
    }

    @Override
    public HtmlResult insertSelective(HttpServletRequest request)  {
        String provinceCodes = request.getParameter("provinceCode");//省份
        String onHooks = request.getParameter("onHook");//挂机方
        String customerLevels = request.getParameter("customerLevels");//客户星级
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String description = request.getParameter("description");//任务描述
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String seatGroupIds = request.getParameter("seatGroup");//被质检班组
        String seatIds = request.getParameter("seatIds");//被质检座席工号
        String customerNums = request.getParameter("customerNum");//客户号码
        String customerloc = request.getParameter("customerloc");//客户归属地
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//重复来电
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        String maxItems = request.getParameter("maxItems");//最多条目数
        String modelIds = request.getParameter("modelIds");//模型ID
        String serialNumbers = request.getParameter("serialNumbers");//录音流水
        String serialNumbes = request.getParameter("serialNumber");//录音流水
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute(Constants.SESSION_USER_INFO);
        BusWorkTestWithBLOBs busWorkTest = new BusWorkTestWithBLOBs();
        busWorkTest.setCreateuserid(user.getId());
        Date date = new Date();
        busWorkTest.setCreatetime(date);
        busWorkTest.setLastupdatetime(date);
        busWorkTest.setTestworkname("模型测检任务");
        busWorkTest.setProstatus(BaseEntity.TASK_PROSTATUS_BEGIN);
        if (!Strings.isNullOrEmpty(callTags)) {
            busWorkTest.setCalltags(callTags);
        }
        if (!Strings.isNullOrEmpty(sysTags)) {
            busWorkTest.setSystags(sysTags);
        }
        if (!Strings.isNullOrEmpty(customerSign)) {
            busWorkTest.setCustomersign(Integer.parseInt(customerSign));
        }
        if (!Strings.isNullOrEmpty(callDirection)) {
            busWorkTest.setCalldirection(Integer.parseInt(callDirection));
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            busWorkTest.setRecallflag(Integer.parseInt(reCallFlag));
        }
        if (!Strings.isNullOrEmpty(maxItems)) {
            busWorkTest.setMaxitems(Integer.parseInt(maxItems));
        }
        if (!Strings.isNullOrEmpty(satisfaction)) {
            busWorkTest.setSatisfaction(satisfaction);
        }
        if (!Strings.isNullOrEmpty(satisfaction)) {
            busWorkTest.setSatisfaction(satisfaction);
        }
        if (!Strings.isNullOrEmpty(customerNums)) {
            busWorkTest.setCustomernums(customerNums);
        }
        if (!Strings.isNullOrEmpty(customerloc)) {
            busWorkTest.setCustomerloc(customerloc);
        }
        if (!Strings.isNullOrEmpty(seatIds)) {
            busWorkTest.setSeatids(seatIds);
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            busWorkTest.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(callEndTime)) {
            busWorkTest.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        }
        if (!Strings.isNullOrEmpty(seatGroupIds)) {
            busWorkTest.setSeatgroupids(seatGroupIds);
        } else {
            //todo坐席组别为空时默认添加该登录角色下可操作的班组
            List<Long> seatGroupIdList = (List<Long>) session.getAttribute("groupIds");
            if (seatGroupIdList != null) {
                busWorkTest.setSeatgroupids(StringUtils.join(seatGroupIdList, ","));
            }
        }
        if (!Strings.isNullOrEmpty(description)) {
            busWorkTest.setDescription(description);
        }
        if (!Strings.isNullOrEmpty(provinceCodes)) {
            busWorkTest.setProvincecode(provinceCodes);
        }
        if (!Strings.isNullOrEmpty(onHooks)) {
            busWorkTest.setOnhooks(onHooks);
        }
        if (!Strings.isNullOrEmpty(customerLevels)) {
            busWorkTest.setCustomerlevels(customerLevels);
        }
        if (!Strings.isNullOrEmpty(minDuration)) {
            busWorkTest.setMinduration(Double.parseDouble(minDuration));
        }
        if (!Strings.isNullOrEmpty(maxDuration)) {
            busWorkTest.setMaxduration(Double.parseDouble(maxDuration));
        }
        if (!Strings.isNullOrEmpty(serialNumbes)) {
            busWorkTest.setSerialnumbers(serialNumbes);
        }
        if (!Strings.isNullOrEmpty(serialNumbers)) {
            busWorkTest.setTotalnumber(serialNumbers.split(",").length);
        } else {
            busWorkTest.setTotalnumber(getAudioNumByTask(request, "【添加质检任务Impl】"));
        }
        int add = busWorkTestMapper.insertSelective(busWorkTest);
        if (add == 0) {
            return HtmlResult.failure("数据添加失败");
        }
        BusWorkTestWithBLOBs workTest = busWorkTestMapper.selectByPrimaryKey(busWorkTest.getId());
        workTest.setTestworkname("模型测检任务_" + workTest.getId());
        busWorkTestMapper.updateByPrimaryKeySelective(workTest);
        if (!Strings.isNullOrEmpty(modelIds)) {
            for (String id : modelIds.split(",")) {
                BusWktModel busWktModel = new BusWktModel();
                busWktModel.setWorkid(busWorkTest.getId());
                busWktModel.setModelid(Long.parseLong(id));
                busWktModelMapper.insertSelective(busWktModel);
            }
        }
        List<String> serialNumberList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(serialNumbers)) {
            serialNumberList.addAll(Arrays.asList(serialNumbers.split(",")));
        }
        //todo异步添加流水号
        ThreadExecutorUtil.executeTask(new WorkTestThread(busWorkTest.getId(), busWktVoiceMapper, serialNumberList));
        return HtmlResult.success("数据添加成功");
    }

    /**
     * 查询检测数据量
     * @param request -
     * @return -
     */
    private int getAudioNumByTask(HttpServletRequest request, String logTxt) {
        BoolQueryBuilder boolQuery = this.formatQuery(request, logTxt);
        BoolQueryBuilder shuldQ = new BoolQueryBuilder();
        for (Integer proS : esUtil.audioSttYesList()) {
            shuldQ.should(QueryBuilders.matchQuery("voiceInfo.proStatus", proS));
        }
        boolQuery.must(shuldQ);
        int count = 1000;
        String maxItems = request.getParameter("maxItems");//最多条目数
        if (maxItems != null) {
            count = Integer.parseInt(maxItems);
        }
        int num = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        if (num > count) {
            return count;
        }
        return num;
    }

    @Override
    public HtmlResult updateByPrimaryKeySelective(HttpServletRequest request) {
        String workId = request.getParameter("id");//任务id
        BusWorkTestWithBLOBs busWorkTest = busWorkTestMapper.selectByPrimaryKey(Long.parseLong(workId));
        if (busWorkTest == null) {
            return HtmlResult.failure("没有此条数据");
        }
        BusWktModelExample modelExample = new BusWktModelExample();
        modelExample.createCriteria().andWorkidEqualTo(Long.parseLong(workId));
        if (busWktModelMapper.deleteByExample(modelExample) == 0) {
            return HtmlResult.failure("任务对应的规则信息更新失败");
        }
        BusWktVoiceExample voiceExample = new BusWktVoiceExample();
        voiceExample.createCriteria().andTestworkidEqualTo(Long.parseLong(workId));
        if (!busWktVoiceMapper.selectByExample(voiceExample).isEmpty()) {
            if (busWktVoiceMapper.deleteByExample(voiceExample) == 0) {
                return HtmlResult.failure("任务对应的语音信息更新失败");
            }
        }
        String modelIds = request.getParameter("modelIds");//模型ID
        if (!Strings.isNullOrEmpty(modelIds)) {
            for (String id : modelIds.split(",")) {
                BusWktModel busWktModel = new BusWktModel();
                busWktModel.setWorkid(Long.parseLong(workId));
                busWktModel.setModelid(Long.parseLong(id));
                busWktModelMapper.insertSelective(busWktModel);
            }
        }
        String serialNumbers = request.getParameter("serialNumbers");//录音流水
        String serialNumbes = request.getParameter("serialNumber");//录音流水
        String maxItems = request.getParameter("maxItems");//最多条目数
        List<String> serialNumberList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(serialNumbers)) {
            serialNumberList.addAll(Arrays.asList(serialNumbers.split(",")));
            busWorkTest.setTotalnumber(serialNumberList.size());
        }
        //todo异步添加流水号
        ThreadExecutorUtil.executeTask(new WorkTestThread(Long.parseLong(workId), busWktVoiceMapper, serialNumberList));
        String provinceCodes = request.getParameter("provinceCode");//省份
        String onHooks = request.getParameter("onHook");//挂机方
        String customerLevels = request.getParameter("customerLevels");//客户星级
        String minDuration = request.getParameter("minDuration");//语音最短时长
        String maxDuration = request.getParameter("maxDuration");//语音最长时长
        String description = request.getParameter("description");//任务描述
        String callStartTime = request.getParameter("callStartTime");//通话开始时间
        String callEndTime = request.getParameter("callEndTime");//通话结束时间
        String seatGroupIds = request.getParameter("seatGroup");//被质检班组
        String seatIds = request.getParameter("seatIds");//被质检座席工号
        String customerNums = request.getParameter("customerNum");//客户号码
        String customerloc = request.getParameter("customerloc");//客户归属地
        String satisfaction = request.getParameter("satisfaction");//满意度
        String reCallFlag = request.getParameter("reCallFlag");//满意度
        String customerSign = request.getParameter("customerSign");//重点客户
        String callDirection = request.getParameter("callDirection");//呼叫类型
        String callTags = request.getParameter("callTags");//话务小结
        String sysTags = request.getParameter("sysTags");//系统标签
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
        if (!Strings.isNullOrEmpty(callTags)) {
            busWorkTest.setCalltags(callTags);
        } else {
            busWorkTest.setCalltags(null);
        }
        if (!Strings.isNullOrEmpty(sysTags)) {
            busWorkTest.setSystags(sysTags);
        } else {
            busWorkTest.setSystags(null);
        }
        if (!Strings.isNullOrEmpty(customerSign)) {
            busWorkTest.setCustomersign(Integer.parseInt(customerSign));
        } else {
            busWorkTest.setCustomersign(null);
        }
        if (!Strings.isNullOrEmpty(callDirection)) {
            busWorkTest.setCalldirection(Integer.parseInt(callDirection));
        } else {
            busWorkTest.setCalldirection(null);
        }
        if (!Strings.isNullOrEmpty(reCallFlag)) {
            busWorkTest.setRecallflag(Integer.parseInt(reCallFlag));
        } else {
            busWorkTest.setRecallflag(null);
        }
        if (!Strings.isNullOrEmpty(maxItems)) {
            busWorkTest.setMaxitems(Integer.parseInt(maxItems));
        }
        if (!Strings.isNullOrEmpty(satisfaction)) {
            busWorkTest.setSatisfaction(satisfaction);
        }  else {
            busWorkTest.setSatisfaction(null);
        }
        if (!Strings.isNullOrEmpty(customerNums)) {
            busWorkTest.setCustomernums(customerNums);
        } else {
            busWorkTest.setCustomernums(null);
        }
        if (!Strings.isNullOrEmpty(customerloc)) {
            busWorkTest.setCustomerloc(customerloc);
        } else {
            busWorkTest.setCustomerloc(null);
        }
        if (!Strings.isNullOrEmpty(seatIds)) {
            busWorkTest.setSeatids(seatIds);
        } else {
            busWorkTest.setSeatids(null);
        }
        if (!Strings.isNullOrEmpty(callStartTime)) {
            busWorkTest.setCallstarttime(DateFormatUtil.stringToDate(callStartTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        } else {
            busWorkTest.setCallstarttime(null);
        }
        if (!Strings.isNullOrEmpty(callEndTime)) {
            busWorkTest.setCallendtime(DateFormatUtil.stringToDate(callEndTime, DateFormatUtil.yyyy_MM_dd_HH_mm_ss));
        } else {
            busWorkTest.setCallendtime(null);
        }
        if (!Strings.isNullOrEmpty(seatGroupIds)) {
            busWorkTest.setSeatgroupids(seatGroupIds);
        } else {
            busWorkTest.setSeatgroupids(null);
        }
        if (!Strings.isNullOrEmpty(description)) {
            busWorkTest.setDescription(description);
        } else {
            busWorkTest.setDescription(null);
        }
        if (!Strings.isNullOrEmpty(provinceCodes)) {
            busWorkTest.setProvincecode(provinceCodes);
        } else {
            busWorkTest.setProvincecode(null);
        }
        if (!Strings.isNullOrEmpty(onHooks)) {
            busWorkTest.setOnhooks(onHooks);
        } else {
            busWorkTest.setOnhooks(null);
        }
        if (!Strings.isNullOrEmpty(customerLevels)) {
            busWorkTest.setCustomerlevels(customerLevels);
        } else {
            busWorkTest.setCustomerlevels(null);
        }
        if (!Strings.isNullOrEmpty(minDuration)) {
            busWorkTest.setMinduration(Double.parseDouble(minDuration));
        } else {
            busWorkTest.setMinduration(null);
        }
        if (!Strings.isNullOrEmpty(maxDuration)) {
            busWorkTest.setMaxduration(Double.parseDouble(maxDuration));
        } else {
            busWorkTest.setMaxduration(null);
        }
        if (!Strings.isNullOrEmpty(serialNumbes)) {
            busWorkTest.setSerialnumbers(serialNumbes);
        } else {
            busWorkTest.setSerialnumbers(null);
        }
        busWorkTest.setLastupdatetime(new Date());
        busWorkTest.setLastupdateuserid(user.getId());
        if (Strings.isNullOrEmpty(serialNumbers)) {
            busWorkTest.setTotalnumber(getAudioNumByTask(request, "【修改质检任务Impl】"));
        }
        if (busWorkTestMapper.updateByPrimaryKeyWithBLOBs(busWorkTest) == 0) {
            return HtmlResult.failure("数据更新失败");
        }
        return HtmlResult.success("数据更新成功");
    }

    @Override
    public HtmlResult deleteByPrimaryKey(String ids) {
        for (String id : ids.split(",")) {
            if (busWorkTestMapper.deleteByPrimaryKey(Long.parseLong(id)) != 0) {
                BusWktModelExample example = new BusWktModelExample();
                example.createCriteria().andWorkidEqualTo(Long.parseLong(id));
                busWktModelMapper.deleteByExample(example);

                BusWktVoiceExample example1 = new BusWktVoiceExample();
                example1.createCriteria().andTestworkidEqualTo(Long.parseLong(id));
                busWktVoiceMapper.deleteByExample(example1);
            }
        }
        return HtmlResult.success("删除数据成功");
    }

    @Override
    public HtmlResult startTask(HttpServletRequest request) throws IOException {
        String ids = request.getParameter("id");//任务id
        Integer startOrStop = Integer.parseInt(request.getParameter("startOrStop"));//启动/停止
        String sOs = startOrStop == 0?"停止" : "启动";
        StringBuilder successSb = new StringBuilder();
        StringBuilder errorSb = new StringBuilder();
        StringBuilder allSb = new StringBuilder();
        for (String workId : ids.split(",")) {
            //判断模型是否上线
            BusWktModelExample exampleW = new BusWktModelExample();
            exampleW.createCriteria().andWorkidEqualTo(Long.parseLong(workId));
            List<BusWktModel> wktModels = busWktModelMapper.selectByExample(exampleW);
            if (wktModels.isEmpty()) {
                errorSb.append("ID = ").append(workId).append("的任务没有模型信息").append("\n\n");
                allSb.append("ID = ").append(workId).append("的任务没有模型信息").append("\n\n");
                continue;
            }
            //有模型未上线
            int continueBool = 0;
            for (BusWktModel model : wktModels) {
                BusModel model1 = busModelMapper.selectByPrimaryKey(model.getModelid());
                if (model1 == null) {
                    errorSb.append("ID = ").append(workId).append("的任务没有模型信息").append("\n\n");
                    allSb.append("ID = ").append(workId).append("的任务没有模型信息").append("\n\n");
                    continue;
                }
                if (model1.getPoststatus() == BaseEntity.MODEL_ONLINE_NO) {
                    errorSb.append("ID = ").append(workId).append("的任务，模型[").append(model1.getName()).append("]未上线").append("\n\n");
                    allSb.append("ID = ").append(workId).append("的任务，模型[").append(model1.getName()).append("]未上线").append("\n\n");
                    continueBool ++;
                }
            }
            if (continueBool > 0) {
                continue;
            }
            BusWorkTest busWorkTest = busWorkTestMapper.selectByPrimaryKey(Long.parseLong(workId));
            if (busWorkTest == null) {
                errorSb.append("没有ID = ").append(workId).append("的任务").append("\n\n");
                allSb.append("没有ID = ").append(workId).append("的任务").append("\n\n");
                continue;
            }
            Map<String, Object> param = new HashMap<>();
            param.put("workId", busWorkTest.getId());
            param.put("flag", BaseEntity.PREQUALITY_PRE_TEST);
            param.put("isStart", startOrStop);
            String response = HttpUtil.sendJsonHttpPost(PropertiesUtil.getProperty("sendTaskToDispatch"), JSONObject.fromObject(param).toString());
            logger.info("【启动质检任务】质检任务" +sOs + "请求接口返回值" + response);
            JSONObject classify = JSONObject.fromObject(response);
            int rtnCode = classify.getInt("rtnCode");
            if (rtnCode != 0) {
                errorSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(classify.getString("rtnMsg"))
                        .append(startOrStop).append("失败").append("\n\n");
                allSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(classify.getString("rtnMsg"))
                        .append(startOrStop).append("失败").append("\n\n");
                continue;
            }
            BusWorkTestWithBLOBs workTest = new BusWorkTestWithBLOBs();
            workTest.setId(busWorkTest.getId());
            if (startOrStop == 1) {
                workTest.setOnsettime(new Date());
            }
            workTest.setProstatus(startOrStop);
            Date date = new Date();
            workTest.setLastupdatetime(date);
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute("userInfo");
            workTest.setLastupdateuserid(user.getId());
            workTest.setLastupdatetime(date);
            if (busWorkTestMapper.updateByPrimaryKeySelective(workTest) == 0) {
                errorSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                allSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                continue;
            }
            //TODO修改model的是否测检属性
            if (startOrStop == 1) {
                BusWktModelExample example = new BusWktModelExample();
                example.createCriteria().andWorkidEqualTo(busWorkTest.getId());
                BusModel busModel = busModelService.selectByPrimaryKey(busWktModelMapper.selectByExample(example).get(0).getModelid());
                busModel.setTesttimes(1);
                if (busModelMapper.updateByPrimaryKeySelective(busModel) == 0) {
                    errorSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                    allSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("失败").append("\n\n");
                    continue;
                }
            }
            successSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("成功").append("\n\n");
            allSb.append("任务[").append(busWorkTest.getTestworkname()).append("]").append(startOrStop).append("成功").append("\n\n");
        }
        if (Strings.isNullOrEmpty(successSb.toString())) {
            return HtmlResult.failure(errorSb.toString());
        } else if (Strings.isNullOrEmpty(errorSb.toString())) {
            return HtmlResult.success(successSb.toString());
        }
        return HtmlResult.tips(allSb.toString());
    }

    @Override
    public HtmlResult selectByExample(HttpServletRequest request) {
        String workId = request.getParameter("id");//任务id
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        boolQuery.must(QueryBuilders.nestedQuery("testInfos", QueryBuilders.matchQuery("testInfos.workId", workId), ScoreMode.None));
        List<Source> sources = new ArrayList<>();
        //总条数
        Integer sumN = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        //单词查询条数
        int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
        List<Integer> pageTout = TaskUtil.formatSum(sumN, excleMax);//todo最后一个数字需要特殊处理:6022
        String[] includes = new String[]
                {
                        "serialNumber",
                        "testInfos"
                };
        for (Integer aPageTout : pageTout) {
            List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                    SystemStatic.AUDIO_ES_INDEX,
                    SystemStatic.AUDIO_ES_TYPE,
                    aPageTout,
                    excleMax,
                    boolQuery,
                    "",
                    "",
                    includes
            );
            if (docList.isEmpty()) continue;
            sources.addAll(esUtil.strs2Entitys(docList));
        }
        Map<String, Integer> sum = new HashMap<>();
        for (Source source : sources) {
            for (TestInfos testInfo : source.getTestInfos()) {
                if (workId.equals(testInfo.getWorkId().toString())) {
                    for (TestModelRules test : testInfo.getTestModelRules()) {
                        sum.merge(test.getModelId() + "_" + test.getRuleId() + "_" + source.getSerialNumber(), 1, (a, b) -> (a + b));
                    }
                }
            }
        }
        List<Map<String, Object>> resultMap = new ArrayList<>();
        for (Map.Entry<String, Integer> map : sum.entrySet()) {
            String[] key = map.getKey().split("_");
            Integer value = map.getValue();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("count", value);
            map1.put("modelId", key[0]);
            map1.put("modelName", busModelMapper.selectByPrimaryKey(Long.parseLong(key[0])).getName());
            map1.put("ruleId", key[1]);
            BusModelRuleExample example = new BusModelRuleExample();
            example.createCriteria().andModelidEqualTo(Long.parseLong(key[1]));
            map1.put("ruleName", busModelRuleMapper.selectByExample(example).get(0).getRulename());
            map1.put("audioIds", key[2]);
            resultMap.add(map1);
        }
        return HtmlResult.success(resultMap);
    }

    @Override
    public HtmlResult getAudioMessage(HttpServletRequest request, String logTxt) {
        String maxItems = request.getParameter("maxItems");//最多条目数
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        BoolQueryBuilder boolQuery = formatQuery(request, logTxt);
        BoolQueryBuilder shuldQ = new BoolQueryBuilder();
        for (Integer proS : esUtil.audioSttYesList()) {
            shuldQ.should(QueryBuilders.matchQuery("voiceInfo.proStatus", proS));
        }
        boolQuery.must(shuldQ);
        int count = 1000;
        if (!Strings.isNullOrEmpty(maxItems)) {
            count = Integer.parseInt(maxItems);
        }
        int size = Integer.parseInt(pageSize);
        if ((Integer.parseInt(pageNum) + Integer.parseInt(pageSize)) > count) {
            size = count % Integer.parseInt(pageSize);
        }
        String[] includes = new String[]
                {
                        "serialNumber",
                        "voiceInfo"
                };
        List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                SystemStatic.AUDIO_ES_INDEX,
                SystemStatic.AUDIO_ES_TYPE,
                Integer.parseInt(pageNum),
                size,
                boolQuery,
                SystemStatic.crud.formatCloumn("inputTime", SystemStatic.AUDIO_ES_INDEX),
                "desc",
                includes
        );
        int countEs = Integer.parseInt(SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery).toString());
        if (countEs > count) {
            countEs = count;
        }
        return HtmlResult.success(esUtil.strs2Entitys(docList), countEs);
    }

    @Override
    public HtmlResult getAudioListById(HttpServletRequest request) {
        String id = request.getParameter("id");//任务id
        BusWktVoiceExample example = new BusWktVoiceExample();
        example.createCriteria().andTestworkidEqualTo(Long.parseLong(id));
        List<BusWktVoice> voices = busWktVoiceMapper.selectByExample(example);
        List<List<BusWktVoice>> voiceList = TaskUtil.ControlPaginationString(voices);
        List<Source> sourceList = new ArrayList<>();
        for (List<BusWktVoice> list : voiceList) {
            BoolQueryBuilder boolQuery = new BoolQueryBuilder();
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (BusWktVoice voice : list) {
                shuldQ.should(QueryBuilders.matchQuery("serialNumber", voice.getSerialnumber()));
            }
            boolQuery.must(shuldQ);
            String[] includes = new String[]
                    {
                            "serialNumber",
                            "voiceInfo"
                    };
            List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                    SystemStatic.AUDIO_ES_INDEX,
                    SystemStatic.AUDIO_ES_TYPE,
                    0,
                    list.size(),
                    boolQuery,
                    SystemStatic.crud.formatCloumn("inputTime", SystemStatic.AUDIO_ES_INDEX),
                    "desc",
                    includes
            );
            sourceList.addAll(esUtil.strs2Entitys(docList));
        }
        return HtmlResult.success(sourceList, voices.size());
    }

    @Override
    public HtmlResult getModelListById(HttpServletRequest request) {
        String id = request.getParameter("id");//任务id
        BusWktModelExample example = new BusWktModelExample();
        example.createCriteria().andWorkidEqualTo(Long.parseLong(id));
        List<BusWktModel> models = busWktModelMapper.selectByExample(example);
        List<BusModel> modelList = new ArrayList<>();
        for (BusWktModel model : models) {
            ModelQueryParam modelInfoOV = new ModelQueryParam();
            modelInfoOV.setId(model.getModelid());
            List<BusModel> models1 = busModelMapper.selectByConditionAndMutilTable(modelInfoOV);
            modelList.addAll(models1);
        }
        return HtmlResult.success(modelList);
    }

    @Override
    public HtmlResult getDetailData(HttpServletRequest request) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        String workId = request.getParameter("workId");
        String modelId = request.getParameter("modelId");
        int pageNum = Integer.parseInt(request.getParameter("pageNum"));//起始页
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));//每页条数
        String sortName = request.getParameter("sortName");//排序字段
        String sortOrder = request.getParameter("sortOrder");//排除方式
        Page<BusModelRule> page = new Page<>(pageNum+1, pageSize);
        BusModelRuleExample example = new BusModelRuleExample();
        example.createCriteria().andModelidEqualTo(Long.parseLong(modelId));
        example.setOrderByClause(sortName + " " + sortOrder);
        List<BusModelRule> rules = busModelRuleMapper.selectByExample(page, example);
        for (BusModelRule rule : rules) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("ruleTypeName", rule.getRuletypename());
            resultMap.put("ruleId", rule.getRuleid());
            resultMap.put("ruleName", rule.getRulename());
            resultMap.put("userFor", rule.getUserfor() == BaseEntity.USEFOR_ART ? "人工" : "系统");
            resultMap.put("fateful", rule.getFateful());
            resultMap.put("signscore", rule.getSignscore());
            Map<String, Integer> resMap = phoneCount(busModelRuleMapper, workId, rule.getRuleid(), esUtil,getQuery(workId, rule.getRuleid()));
            resultMap.put("phoneCount", resMap.get("ruleTimes"));
            resultMap.put("scoreCount", resMap.get("allSum"));
            resultMap.put("useCount", 0);
            resultList.add(resultMap);
        }
        return HtmlResult.success(resultList, page.getTotalCount());
    }

    //命中量
    private static Map<String, Integer> phoneCount(
            BusModelRuleMapper busModelRuleMapper, String workId, Long ruleId,
            ESUtil esUtil, BoolQueryBuilder boolQuery
    ) {
        //扣分总数
        int allSum = 0;
        //模型id
        Long modelId = null;
        //致命性
        int fateful = 0;
        //命中量
        int ruleTimes = 0;
        Map<String, Integer> resMap = new HashMap<>();
        resMap.put("ruleTimes", ruleTimes);
        resMap.put("allSum", allSum);
        List<Source> sourceList = new ArrayList<>();
        //总条数
        Integer sumN = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        //单词查询条数
        int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
        List<Integer> pageTout = TaskUtil.formatSum(sumN, excleMax);//todo最后一个数字需要特殊处理:6022
        String[] includes = new String[]
                {
                        "serialNumber",
                        "testInfos"
                };
        for (Integer aPageTout : pageTout) {
            List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                    SystemStatic.AUDIO_ES_INDEX,
                    SystemStatic.AUDIO_ES_TYPE,
                    aPageTout,
                    excleMax,
                    boolQuery,
                    "",
                    "",
                    includes
            );
            if (docList.isEmpty()) continue;
            sourceList.addAll(esUtil.strs2Entitys(docList));
        }
        if (sourceList.size() == 0) {
            return resMap;
        }
        for (Source source : sourceList) {
            for (TestInfos test : source.getTestInfos()) {
                if (workId.equals(test.getWorkId().toString())) {
                    for (TestModelRules tm : test.getTestModelRules()) {
                        if (ruleId.toString().equals(tm.getRuleId().toString())) {
                            //计算得分
                            allSum += tm.getRuleScore();
                            modelId = tm.getModelId();
                            fateful = tm.getFateful();
                            ruleTimes ++;
                        }
                    }
                }
            }
        }
        //最大扣分
        BusModelRuleExample example = new BusModelRuleExample();
        example.createCriteria().andModelidEqualTo(modelId).andRuleidEqualTo(ruleId);
        Integer max = busModelRuleMapper.selectByExample(example).get(0).getMaxscore();
        //计算得分
        if (BaseEntity.FATEFUL_ART == fateful) {//致命性规则
            if (max == null) {
                allSum = -100*ruleTimes;
            } else {
                allSum = max*ruleTimes;
            }
        }
        resMap.put("ruleTimes", ruleTimes);
        resMap.put("allSum", allSum);
        //非致命性规则
        return resMap;
    }

    private static BoolQueryBuilder getQuery(String workId, Long ruleId) {
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        boolQuery.must(
                QueryBuilders.nestedQuery(
                        "testInfos",
                        QueryBuilders.boolQuery()
                                .must(
                                        QueryBuilders.matchQuery("testInfos.workId", workId)
                                )
                                .must(
                                        QueryBuilders.nestedQuery(
                                                "testInfos.testModelRules",
                                                QueryBuilders.matchQuery("testInfos.testModelRules.ruleId", ruleId),
                                                ScoreMode.None
                                        )
                                ),
                        ScoreMode.None
                )
        );
        return boolQuery;
    }

    public Map<String, Object> getPhoneDetailDataQuery(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        String serialNumber = request.getParameter("serialNumber");//录音流水
        String satisfactions = request.getParameter("satisfaction");//满意度
        String workId = request.getParameter("workId");
        String ruleIds = request.getParameter("ruleId");
        String metType = request.getParameter("metType");
        String isHit = request.getParameter("isHit");//是否命中：是(YES)；否(NO)
        String sortName = request.getParameter("sortName");//排序字段
        String sortOrder = request.getParameter("sortOrder");//排除方式
        int pageNum = 0;//起始页
        int pageSize = 0;//每页条数
        if ("search".equals(metType)) {
            pageNum = Integer.parseInt(request.getParameter("pageNum"));//起始页
            pageSize = Integer.parseInt(request.getParameter("pageSize"));//每页条数
        }
        BoolQueryBuilder boolQuery = formatQuery(request, "");
        //任务+规则
        BoolQueryBuilder nestQuery = new  BoolQueryBuilder();
        //满意度
        if (!Strings.isNullOrEmpty(satisfactions)) {
            BoolQueryBuilder shuldQ = new BoolQueryBuilder();
            for (String satisfaction : satisfactions.split(",")) {
                shuldQ.should(QueryBuilders.matchQuery("voiceInfo.satisfaction", satisfaction));
            }
            boolQuery.must(shuldQ);
        }
        if (!Strings.isNullOrEmpty(serialNumber)) {
            boolQuery.must(QueryBuilders.wildcardQuery("serialNumber", "*" + serialNumber + "*"));
        }
        nestQuery.must(QueryBuilders.matchQuery("testInfos.workId", workId));
        //是否命中条件
        NestedQueryBuilder existsQ = new NestedQueryBuilder(
                "testInfos.testModelRules",
                QueryBuilders.existsQuery("testInfos.testModelRules.ruleId"),
                ScoreMode.None
        );
        if ("1".equals(isHit) && Strings.isNullOrEmpty(ruleIds)) {//是否命中：是；规则：全部
            nestQuery.must(existsQ);
        } else if ("1".equals(isHit) && !Strings.isNullOrEmpty(ruleIds)) {//是否命中：是；规则：具体规则
            BoolQueryBuilder query = new BoolQueryBuilder();
            if (!Strings.isNullOrEmpty(ruleIds)) {
                for (String ruleId : ruleIds.split(",")) {
                    query.should(QueryBuilders.matchQuery("testInfos.testModelRules.ruleId", ruleId));
                }
            }
            nestQuery.must(QueryBuilders.nestedQuery("testInfos.testModelRules", query, ScoreMode.None));

        } else if ("0".equals(isHit) && Strings.isNullOrEmpty(ruleIds)) {//是否命中：否；规则：全部
            nestQuery.mustNot(existsQ);
        } else if ("0".equals(isHit) && !Strings.isNullOrEmpty(ruleIds)) {//是否命中：否；规则：具体规则
            BoolQueryBuilder query = new BoolQueryBuilder();
            if (!Strings.isNullOrEmpty(ruleIds)) {
                for (String ruleId : ruleIds.split(",")) {
                    query.should(QueryBuilders.matchQuery("testInfos.testModelRules.ruleId", ruleId));
                }
            }
            nestQuery.mustNot(QueryBuilders.nestedQuery("testInfos.testModelRules", query, ScoreMode.None));
        }
        //组装条件
        boolQuery.must(
                QueryBuilders.nestedQuery(
                        "testInfos",
                        nestQuery,
                        ScoreMode.None
                )
        );
        List<VoiceInfoDto> voiceInfoDtoList = new ArrayList<>();
        //总条数
        Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        String[] includes = new String[]
                {
                        "serialNumber",
                        "voiceInfo"
                };
        if (!"search".equals(metType)) {
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                        SystemStatic.AUDIO_ES_INDEX,
                        SystemStatic.AUDIO_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                        sortOrder,
                        includes
                );
                if (docList.isEmpty()) continue;
                voiceInfoDtoList.addAll(esUtil.formatModel(docList));
            }
        } else {
            List<String> docList = SystemStatic.crud.queryMapQBuilderRetRuleAndWork(
                    SystemStatic.AUDIO_ES_INDEX,
                    SystemStatic.AUDIO_ES_TYPE,
                    pageNum,
                    pageSize,
                    boolQuery,
                    SystemStatic.crud.formatCloumn(sortName, SystemStatic.AUDIO_ES_INDEX),
                    sortOrder,
                    includes
            );
            if (!docList.isEmpty()) {
                voiceInfoDtoList.addAll(esUtil.formatModel(docList));
            }
        }
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("count", SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery));
        resMap.put("data", voiceInfoDtoList);
        return resMap;
    }

    @Override
    public List<BusModel> selectDateList(Map<String, Object> map) {
        return busWorkTestMapper.selectDateList(map);
    }

    @Override
    public HtmlResult getPhoneDetailData(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        Map<String, Object> infos = getPhoneDetailDataQuery(request);
        return HtmlResult.success(infos.get("data"), infos.get("count"));
    }
}
